const router = require('koa-router')()
const userserver = require('../controllers/mySqlConfig')
router.prefix('/user')//公共前缀

//通常情况下请求参数的时候需要传递数据给后端的时候用post,或者用到数据库用post.

//登录的接口//koa无法解析post请求参数
router.post('/userlogin',async (ctx,next)=>{
    //拿到前端给我的参数
    let _username = ctx.request.body.username
    let _password = ctx.request.body.password

    // console.log(_username,_password);
    //去数据库匹配账号密码
    // userlogin().then()
    await userserver.userlogin(_username,_password)
    .then((res)=>{
        console.log(res);
        //向前端返回内容
        if(res.length){
            let result = {
                id:res[0].id || 1,
                nickname:res[0].nickname,
                username:res[0].username,
            }
            ctx.body = {
                code:200,
                data:result,
                mess:'登录成功'
            }
        }else{
            ctx.body = {
                code:405,
                data:'error',
                mess:'账号或密码有误'
            }
        }
        
    }).catch(err =>{
        ctx.body = {
            code:'404',
            data: err,
            mess:'服务器正在开小差'
        }
    })
})
//注册
router.post('/userRegister',async (ctx,next) =>{
    //拿到前端给的参数
    // let _username = ctx.request.body.username
    // let _password = ctx.request.body.password
    // let _nickname = ctx.request.body.nickname
    let {username,password,nickname} = ctx.request.body
    if(!username|| !password || !nickname){
        ctx.body = {
            code: 406,
            mess: '用户名密码或昵称不能为空'
        }
        return
    }
    await userserver.findUser(username)
    .then(async res=>{
        // console.log(res);
        if(res.length){
            ctx.body = {
                code:'500',
                mess:'账号已存在'
            }
        }else{
        await userserver.insertUser([username,password,nickname]).then(res=>{
            // console.log(res);
            if(res.affectedRows){
                ctx.body = {
                    code:200,
                    data:'ok',
                    mess:'注册成功'
                }
            } else {
                ctx.body = {
                    code:'80001',
                    data:'error',
                    mess:'注册失败'
                }
            }
        })//可以接一个.catch
        }
    })
    //先判断数据库中有没有这个username

})

module.exports = router